"""
TTS合成服务
"""
import os
from typing import Optional
from loguru import logger

from storyforge.models import Episode
from storyforge.providers import TTSProvider
from storyforge.config import get_config, get_provider_config
from storyforge.utils import get_project_dir, load_json, generate_id


class TTSService:
    """TTS服务"""
    
    def __init__(self):
        """初始化服务"""
        self.config = get_config()
    
    def synthesize(
        self,
        project_name: str,
        episode_index: int,
        voice: str = "narrator"
    ) -> str:
        """
        合成TTS音频
        
        Args:
            project_name: 项目名称
            episode_index: 剧集序号
            voice: 音色标识
            
        Returns:
            音频文件路径
        """
        project_dir = get_project_dir(project_name, self.config.paths.projects)
        episode_file = project_dir / f"episode_{episode_index}.json"
        
        episode_data = load_json(str(episode_file))
        if not episode_data:
            raise FileNotFoundError(f"剧集文件不存在: {episode_file}")
        
        episode = Episode(**episode_data)
        
        # 提取对白文本
        dialogue_text = self._extract_dialogue(episode)
        
        if not dialogue_text:
            logger.warning(f"第{episode_index}集没有对白内容")
            return ""
        
        # 获取TTS提供商
        provider_name = self.config.defaultProvider.tts
        provider_config = get_provider_config(provider_name)
        
        if not provider_config:
            raise ValueError(f"TTS提供商配置不存在: {provider_name}")
        
        provider = TTSProvider(provider_config.dict())
        
        logger.info(f"开始TTS合成，音色: {voice}, 文本长度: {len(dialogue_text)}")
        
        # 提交TTS任务
        payload = {
            "text": dialogue_text,
            "voice": voice,
            "speed": 1.0
        }
        
        job_id = provider.submit(payload)
        
        # 轮询结果（实际应该异步处理）
        import time
        for _ in range(10):
            status = provider.poll(job_id)
            if status["status"] == "succeeded":
                result_url = status["result_url"]
                logger.info(f"TTS合成完成: {result_url}")
                
                # 保存音频文件路径（实际应该下载文件）
                outputs_dir = self.config.paths.outputs
                os.makedirs(outputs_dir, exist_ok=True)
                audio_path = os.path.join(outputs_dir, f"ep{episode_index}.wav")
                
                # 实际实现中应该下载result_url到audio_path
                logger.info(f"音频文件路径: {audio_path}")
                return audio_path
            
            time.sleep(1)
        
        raise Exception("TTS合成超时")
    
    def _extract_dialogue(self, episode: Episode) -> str:
        """
        从剧集中提取对白文本（用于TTS合成）
        
        Args:
            episode: 剧集对象
            
        Returns:
            合并后的对白文本字符串
        """
        dialogue_parts = []
        
        script_json = episode.scriptJSON
        scenes = script_json.get("scenes", [])
        
        for scene in scenes:
            if "dialogue" in scene:
                dialogue_parts.append(scene["dialogue"])
        
        if not dialogue_parts:
            # 如果没有场景，使用大纲作为旁白
            if episode.outline:
                dialogue_parts.append(episode.outline)
        
        return "\n".join(dialogue_parts)

